//
//  MNetworkHandler.m
//  MobiProject
//
//  Created by 阔 李 on 15-3-25.
//  Copyright (c) 2015年 阔 李. All rights reserved.
//

#import "MNetworkHandler.h"
#import "MNetworkItem.h"
#import "AFNetworking.h"


#import <MobileCoreServices/MobileCoreServices.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperationManager.h"
#import <Availability.h>

@implementation MNetworkHandler

+ (MNetworkHandler *) sharedInstance
{
    static MNetworkHandler * handler = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        handler = [[MNetworkHandler alloc] init];
    });
    
    return handler;
}

- (BOOL)cancelForDelegate:(id)delelgate
{
    NSUInteger hashValue = [delelgate hash];
    
    BOOL flag = NO;
    
    for (MNetworkItem *item in self.networkItems)
    {
        if (item.hashValue == hashValue) 
        {
            [self removeItem:item];
            flag = YES;
        }
    }
    
    return flag;
}

- (void)addItem:(MNetworkItem *)networkItem
{
    if (networkItem.showHUD) 
    {
        _showHUDReqCount++;
    }
    
    [self.networkItems addObject:networkItem];
}

- (void)removeItem:(MNetworkItem *)networkItem
{
    if (networkItem.showHUD) 
    {
        _showHUDReqCount--;
    }
    
   // [networkItem.httpRequest clearDelegatesAndCancel];
    [self.networkItems removeObject:networkItem];
}

- (NSUInteger)conURL:(NSString *) url
         networkType:(NetWorkType) networkType
              params:(NSMutableDictionary *) params
            delegate:(id) delegate
             showHUD:(BOOL) showHUD
        successBlock:(NWSuccessBlock) successBlock
        failureBlock:(NWFailureBlock) failureBlock
{
    /// 如果有一些公共处理，可以写在这里
    
    
    NSUInteger hashValue = [delegate hash];
    MNetworkItem *item = [[MNetworkItem alloc] initWithtype:networkType
                                                          url:url
                                                       params:params
                                                     delegate:delegate
                                                    hashValue:hashValue
                                                      showHUD:showHUD
                                                 successBlock:successBlock
                                                 failureBlock:failureBlock];
    return item.hashValue;
}


@end
